/**
 * Created with IntelliJ IDEA.
 * User: pierre
 * Date: 04/06/13
 * Time: 23:34
 * To change this template use File | Settings | File Templates.
 */
var Map = [];
var Parcelle = [];
var BuildingTab = [];
var CropTab = [];
var socket;
var user;
var clickD = 0;
(function($){
    socket = io.connect();
})(jQuery);

window.onload = function () {
    socket.emit('inGame');
    socket.on('sendMap', function(data){
        Map = data;
        console.log(Map[1].xPos);
        Crafty.scene("loading");
    })
    socket.on('user', function(data){
        user = data;
        
        $('nav badge.red').append(user.money);
    })
    socket.on('sendParcelles', function(data){
        Parcelle = data;
        console.log("parcelles reçues");
        for(var i = 0; i<Parcelle.length;i++){
        console.log(Parcelle[i].fertility);
        }
        Crafty.scene("parcelle_user");
    })
    socket.on('setBuilding', function(building){
        BuildingTab.push(building);
        console.log(BuildingTab);
        switch(building.name){
            case "Silo":
                var newbuild=Crafty.e("2D, DOM, building, Mouse");
                newbuild.attr('z',building.i+20 * building.j+1);
                break;
            case "Barn":
                var newbuild=Crafty.e("2D, DOM, building, Mouse");
                newbuild.attr('z',building.i+20 * building.j+1);
                break;
            case "Cold Storage":
                var newbuild=Crafty.e("2D, DOM, building, Mouse");
                newbuild.attr('z',building.i+20 * building.j+1);
                break;
        }
        userMap.place(building.i, building.j,1,newbuild);
        console.log("NOUVEAU BUILDING");
    })
    socket.on('setCrop', function(crop){
        CropTab.push(crop);
        console.log(CropTab);
        var timer;
        for(var z = 0; z<Parcelle.length; z++){
            if(crop.parcelle_id == Parcelle[z]._id){
                timer = parseInt((Parcelle[z].humidity * (1-(Parcelle[z].fertility/100)+1))*100,10);
            }
        }
        var cron = setInterval(function(){
            for(var i = 0; i<Parcelle.length; i++){
                if(Parcelle[i]._id == crop.parcelle_id){
                    console.log(Parcelle[i]);
                    Parcelle[i].maturity_level += 0.25;
                    Parcelle[i].humidity -=0.10;
                    Parcelle[i].healthy_level -=0.25;
                    console.log("PARCELLE    :" + Parcelle[i].maturity_level);
                    socket.emit('cronParcelle', Parcelle[i]);

                }
            }
            for(var j=0; j<CropTab.length; j++){
                if (CropTab[j].parcelle_id == crop.parcelle_id){
                    CropTab[j].decay_date += 0.25;
                    console.log("CROP" + CropTab[j].decay_date);
                    socket.emit('cronCrop', CropTab[j]);
                }
            }
        }, timer);
        switch(crop.type){
            case "tomatoes":
                var newcro=Crafty.e("2D, DOM, tomatoes, Mouse");
                newcro.attr('z',crop.i+20 * crop.j+1);
                break;
            case "corn":
                var newcro=Crafty.e("2D, DOM, tomatoes, Mouse");
                newcro.attr('z',crop.i+20 * crop.j+1);
                break;
            case "wheat":
                var newcro=Crafty.e("2D, DOM, tomatoes, Mouse");
                newcro.attr('z',crop.i+20 * crop.j+1);
                break;
        }
        userMap.place(crop.i, crop.j,1,newcro);
        console.log("NOUVEAU CROP");
    })
    console.log(Map.length);
    //start crafty

    Crafty.init(800, 600);
    //Crafty.canvas.init();
    Crafty.sprite(64, "/images/sprite.png", { grass: [0,0]});
    Crafty.sprite(64,"/images/smithy.png",{Farm:[0,0]});
    Crafty.sprite(128,"/images/building.png", {building:[0,0]});
    Crafty.sprite(64,"/images/tomato.png", {tomatoes:[0,0]});

    var map = Crafty.isometric.size(64);
    var userMap = Crafty.isometric.size(64);

    var z = 0;
    var zd = 10;
    Crafty.scene("loading", function () {
        //load takes an array of assets and a callback when complete
        Crafty.load(["/images/sprite.png"], function () {
            Crafty.scene("main"); //when everything is loaded, run the main scene
        });

        //black background with some loading text
        Crafty.background("#124");
        Crafty.e("2D, DOM, Text").attr({ w: 100, h: 20, x: 150, y: 120 })
            .text("Loading")
            .css({ "text-align": "center" });
    });

//automatically play the loading scene

    Crafty.scene("main", function () {
        generateWorld();
    });

    function generateWorld(){
             for(var i=0; i<Map.length; i++){
                if(Map[i].user_mail == ""){
                        var tile = Crafty.e("2D", "DOM","grass", "Mouse")
                            .attr('z',Map[i].xPos+20 * Map[i].yPos+1)
                            .attr('i', i)
                            .areaMap([32,0],[64,16],[64, 48],[32,64],[0,48],[0, 16])
                            .bind("Click", function(e) {
                                //destroy on right click
                                //right click seems not work in Mac OS
                                //delete it
                                console.log(this.i);

                            }).bind("MouseOver", function() {
                                if(this.has("grass")){
                                    this.sprite(0,1);
                                }
                            }).bind("MouseOut", function() {
                                if(this.has("grass")){
                                    this.sprite(0,0);
                                }
                            }).bind("DoubleClick", function(e) {
                                socket.emit('requestParcelles', {zone_id: Map[this.i]._id, zone_user: Map[this.i].user_mail})
                            });
                        map.place(Map[i].xPos,Map[i].yPos,0,tile);
                        map.place(Map[i].xPos,Map[i].yPos,0,tile);
                }else{
                    var tile = Crafty.e("2D", "DOM","grass", "Mouse")
                        .attr('z',Map[i].xPos+20 * Map[i].yPos+1)
                        .attr('i', i)
                        .areaMap([32,0],[64,16],[64, 48],[32,64],[0,48],[0, 16])
                        .bind("MouseOver", function() {
                            if(this.has("grass")){
                                this.sprite(0,1);
                            }
                        }).bind("MouseOut", function() {
                            if(this.has("grass")){
                                this.sprite(0,0);
                            }
                        }).bind("DoubleClick", function(e) {
                            socket.emit('requestParcelles', {zone_id: Map[this.i]._id, zone_user: Map[this.i].user_mail})
                        });
                    var tile2 = Crafty.e("2D", "DOM","Farm").attr('z',Map[i].xPos+20 * Map[i].yPos+1)

                    map.place(Map[i].xPos,Map[i].yPos,0,tile);
                    map.place(Map[i].xPos,Map[i].yPos,1,tile2)
                }

             }
        }

    Crafty.addEvent(this, Crafty.stage.elem, "mousedown", function(e) {
        if(e.button > 1) return;
        var base = {x: e.clientX, y: e.clientY};

        function scroll(e) {
            var dx = base.x - e.clientX,
                dy = base.y - e.clientY;
            base = {x: e.clientX, y: e.clientY};
            Crafty.viewport.x -= dx;
            Crafty.viewport.y -= dy;
        };

        Crafty.addEvent(this, Crafty.stage.elem, "mousemove", scroll);
        Crafty.addEvent(this, Crafty.stage.elem, "mouseup", function() {
            Crafty.removeEvent(this, Crafty.stage.elem, "mousemove", scroll);
        });
    });

    Crafty.scene("parcelle_user", function(){
        var longueur = Parcelle.length;
        console.log(longueur)
        console.log('Je dessine ma User Map');
        var i = 0, j = 0;
        var player = Crafty.e("2D, DOM, Farm, Mouse")
            .attr("i", i)
            .attr("j", j)
            .attr('z',i+20 * j+1);
        userMap.place(i,j,1, player);
        for ( i = 0; i<longueur/20; i++ ){
           for ( j = 0; j< longueur/5; j++){
               var tile = Crafty.e("2D, DOM, grass, Mouse")
                   .attr('z',i+20 * j+1)
                   .attr('i', i)
                   .attr('j', j)
                   .areaMap([32,0],[64,16],[64, 48],[32,64],[0,48],[0, 16])
                   .bind("Click", function(){

                       console.log("I :"+ this.i+ "J :" + this.j);
                       console.log("Parcelle ID" + Parcelle[this.i+this.j]._id);
                       if(player.i==this.i){
                               var y = player.j;
                                while(y != this.j){
                                   player.attr('z',i+20 * j+1);
                                   console.log(player.i + y);
                                   userMap.place(player.i,y,1,player);
                                   y++;
                                }
                       }

                   }).bind('MouseUp', function(e){
                       if(e.button == Crafty.mouseButtons.RIGHT){
                           console.log("click DROIT");
                           switch(clickD){
                               case 1:
                                   var newbuilding=Crafty.e("2D, DOM, tomatoes, Mouse")
                                   var crop = new Crops();
                                   crop.type = "tomatoes";
                                   crop.price = 1;
                                   crop.productivity = 10;
                                   crop.maturation_date = 15;
                                   crop.decay_time = 30;
                                   crop.decay_date = 0;
                                   crop.parcelle_id = Parcelle[this.i+this.j]._id;
                                   crop.i = this.i;
                                   crop.j = this.j;
                                   CropTab.push(crop);
                                   newbuilding.attr('z',i+20 * j+1);
                                   var fert = Parcelle[this.i+this.j].fertility/100;
                                   var timer = (Parcelle[this.i+this.j].humidity*(1-fert)+1)*10000;
                                   console.log(timer);
                                   Growing(Parcelle[this.i+this.j]._id, Parcelle[this.i+this.j].fertility, Parcelle[this.i+this.j].humidity);
                                    break;
                               case 2:
                                   var newbuilding=Crafty.e("2D, DOM, tomatoes, Mouse");
                                   var crop = new Crops();
                                   crop.type = "corn";
                                   crop.price = 2;
                                   crop.productivity = 10;
                                   crop.maturation_date = 15;
                                   crop.decay_time = 30;
                                   crop.decay_date = 0;
                                   crop.parcelle_id = Parcelle[this.i+this.j]._id;
                                   crop.i = this.i;
                                   crop.j = this.j;
                                   CropTab.push(crop);
                                   newbuilding.attr('z',i+20 * j+1);

                                   break;
                               case 3:
                                   var newbuilding=Crafty.e("2D, DOM, tomatoes, Mouse");
                                   var crop = new Crops();
                                   crop.type = "wheat";
                                   crop.price = 3;
                                   crop.productivity = 10;
                                   crop.maturation_date = 15;
                                   crop.decay_time = 30;
                                   crop.decay_date = 0;
                                   crop.parcelle_id = Parcelle[this.i+this.j]._id;
                                   crop.i = this.i;
                                   crop.j = this.j;
                                   CropTab.push(crop);
                                   newbuilding.attr('z',i+20 * j+1);
                                   break;
                               case 4:
                                   var newbuilding=Crafty.e("2D, DOM, building, Mouse");
                                   var building = new Building();
                                   building.name="Silo";
                                   building.Capacity=10;
                                   building.power = 2;
                                   building.price = 20;
                                   building.whitering = 2;
                                   building.parcelle_id = Parcelle[this.i+this.j]._id;
                                   building.i = this.i;
                                   building.j = this.j;
                                   BuildingTab.push(building);
                                   newbuilding.attr('z',i+20 * j+1);
                                   break;
                               case 5:
                                   var newbuilding=Crafty.e("2D, DOM, building, Mouse");
                                   var building = new Building();
                                   building.name="Barn";
                                   building.Capacity=20;
                                   building.power = 4;
                                   building.price = 40;
                                   building.whitering = 2;
                                   building.parcelle_id = Parcelle[this.i+this.j]._id;
                                   building.i = this.i;
                                   building.j = this.j;
                                   BuildingTab.push(building);
                                   newbuilding.attr('z',i+20 * j+1);
                                   //userMap.place(this.i,this.j,1,newbuilding);
                                   break;
                               case 6:
                                   var newbuilding=Crafty.e("2D, DOM, building, Mouse");
                                   var building = new Building();
                                   building.name="Cold Storage";
                                   building.Capacity=50;
                                   building.power = 8;
                                   building.price = 80;
                                   building.whitering = 0;
                                   building.parcelle_id = Parcelle[this.i+this.j]._id;
                                   building.i = this.i;
                                   building.j = this.j;
                                   BuildingTab.push(building);
                                   newbuilding.attr('z',i+20 * j+1);
                                   break;
                           }
                           userMap.place(this.i,this.j,1,newbuilding);
                           if(building != null){
                               socket.emit('sendBuilding', building);
                           }
                           if(crop != null){
                           socket.emit('sendCrop', crop);
                           }
                       }
                   })
                   .bind("MouseOver", function() {
                       this.sprite(0,1);
                   }).bind("MouseOut", function() {
                       this.sprite(0,0);
                   }).bind("DoubleClick", function(e) {
                   });
               userMap.place(i,j,0,tile);
           }
        }

        //mouvement avec les positions
        /*Crafty.modules('http://cdn.craftycomponents.com', { MoveTo: 'release' }, function () {
                Crafty.e("2D, DOM, Farm, MoveTo")
                    .attr('z',i+20 * j+1)
                    .attr({x: 0, y: 0});
        });*/
    });
    function Growing(parcelle_id, fertilite, humidite){
        var timer = parseInt((humidite* (1-(fertilite/100)+1))*100,10);
        console.log(timer);
        console.log("je rentre dans ma fonction");
        var cron = setInterval(function(){
           for(var i = 0; i<Parcelle.length; i++){
               if(Parcelle[i]._id == parcelle_id){
                  Parcelle[i].maturity_level += 0.25;
                  Parcelle[i].humidity -=0.10;
                  Parcelle[i].healthy_level -=0.25;
                   console.log(Parcelle[i].maturity_level);
                  socket.emit('cronParcelle', Parcelle[i]);
               }
           }
           for(var j=0; j<CropTab.length; j++){
               if (CropTab[j].parcelle_id == parcelle_id){
                   CropTab[j].decay_date += 0.25;
                   console.log(CropTab[j].decay_date);
                   socket.emit('cronCrop', CropTab[j]);
                   if(CropTab[j].decay_date == CropTab[j].decay_time){
                       this.destroy();
                   }
               }
           }
        }, timer);
    }
};
function newBuilding1()
{
    clickD = 4;
}

function newBuilding2()
{
    clickD = 5;
}
function newBuilding3()
{
    clickD = 6;
}
function newCrop1()
{
    clickD = 1;
}
function newCrop2()
{
    clickD = 2;
}
function newCrop3()
{
    clickD = 3;
}
